////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                                //
//                      Single Linked List's find, insert, delete, functions' implemention code                //
//                                                                                                                                //
//                                                                                                                                //
//                                      Author:    Jack Hui (huiguobin)                                                 //
//                                                                                                                                //
//                                                                                                                                //
////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////functions' implemention file////////////////////////////////

#include "single_linked_list.h"

/*Single Linked List's finding*/
LinkList find_list(LinkList L, int k)
{
	LinkList p = L->link;
	int i = 1;

	if(NULL == p || k <= 0)
	{
		return NULL;
	}

	/* if the linked list is not null and the number has not reach, go on seeking backward. */
	while (NULL != p && i < k) 
	{
		p = p->link;
		i ++;
	}

	/* If found the node, return it. */
	if(NULL != p && i == k)
	{
		return p;
	}
	else
	{
		return NULL;
	}
}


/*Single Linked List's inserting*/
int insert_list(LinkList L, int k, DataType j)
{
	LinkedNode *p = NULL, *q = NULL;
	
	if(L->link == NULL || k < 1)
	{
		return 0;
	}

	/* If it only has one node, p points to the first node. */
	if(k == 1)
	{
		p = L;
	}
	else
	{
		/*If it has one or more nodes, p points to the insert position's previous node.*/
		p = find_list(L, k-1);
		if(NULL == p)
		{
			return 0;
		}
	}

	/* allocate space for the new node.*/
	q = (LinkedNode *)malloc(sizeof(LinkedNode));
	if(NULL == q)
	{
		return 0;
	}
	q->data = j;

	/* Insert the new node into the Linked list.*/
	q->link = p->link;
	p->link = q;
	
	return 1;
}


/*Single Linked List's deleting*/
int delete_list(LinkList L, int k)
{
	LinkedNode *p = NULL, *q = NULL;
	
	if(L->link == NULL || k < 1)
	{
		return 0;
	}

	/*If it only has one node, p points to the first node.*/
	if(k == 1)
	{
		p = L;
	}
	else
	{
		/*If it has one or more nodes, p points to the insert position's previous node.*/
		p = find_list(L, k-1);
		if(NULL == p)
		{
			return 0;
		}
	}

	/*Free the node which to be deleted.*/
	q = p->link;
	p->link = q->link;
	free(q);
	q = NULL;
	return 1;
}
